package cn.org.xwb.bookmall.model.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.org.xwb.bookmall.model.po.Manager;
import cn.org.xwb.bookmall.model.mapper.ManagerMapper;
import cn.org.xwb.bookmall.model.po.User;
import cn.org.xwb.bookmall.model.properties.AccountProp;
import cn.org.xwb.bookmall.model.service.IManagerService;
import cn.org.xwb.bookmall.model.utils.AccountUtil;
import cn.org.xwb.common.utils.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author xwb
 * @since 2023-11-23
 */
@Service
public class ManagerServiceImpl extends ServiceImpl<ManagerMapper, Manager> implements IManagerService {

    @Autowired
    private AccountUtil accountUtil;

    @Autowired
    private AccountProp accountProp;

    /**
     * 根据邮箱查询管理员
     *
     * @param mail
     * @return
     */
    @Override
    public Manager findManagerByMail(String mail) {
        LambdaQueryWrapper<Manager> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Manager::getMail, mail);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据邮箱查找管理员，如果管理员不存在则创建管理员并返回
     *
     * @param mail
     * @return null-账号被禁用
     */
    @Override
    public Manager findAndGenManagerByMail(String mail) {
        // 查询
        Manager manager = findManagerByMail(mail);
        // 管理员不存在
        if (Objects.isNull(manager)) {
            // 创建管理员
            manager = genManagerByMail(mail);
            // 入库
            baseMapper.insert(manager);
        }
        // 管理员被禁用
        if (manager.getDisabled()) return null;
        return manager;
    }

    /**
     * 根据邮箱生成管理员
     *
     * @param mail
     * @return
     */
    private Manager genManagerByMail(String mail) {
        String account = accountUtil.genAccount();
        return new Manager(
                null,
                accountProp.getDefaultAvatar(),
                null,
                account,
                account,
                mail,
                null,
                RandomUtil.genRandNumLowerUpperStr(accountProp.getPwdSaltLen()),
                DateUtil.date(),
                false
        );
    }
}
